//
//  YMDetailView.swift
//  YMSwiftUI
//
//  Created by anscen on 2022/3/23.
//

import SwiftUI
import SDWebImage
import Alamofire
struct YMDetailView: View {
    
    @State var bookId :String
    @State var model :YMBook = YMBook()
    @State var quene = BaseShelfQueue()
    @State var listData :[YMBook] = []
    @State var listAdap :[GridItem] =  [GridItem(.adaptive(minimum: list_width, maximum: list_width + 10), spacing: 0, alignment: .center)]
    @State var bookCase           = "加入书架"
    @State var isAlertActive      = false
    var body: some View {
        GeometryReader.init { rootSize in
            VStack(alignment: .center, spacing: 10) {
                ScrollView(.vertical, showsIndicators:false) {
                    YMDetailHeadView(model: model)
                    VStack(alignment: .leading, spacing: 0) {
                        if listData.count > 0{
                            Text("同类作品推荐").font(Font(UIFont.boldSystemFont(ofSize: 18))).foregroundColor(.black).padding(EdgeInsets(top:0, leading: 15, bottom: 5, trailing: 15))
                        }
                        LazyVGrid(columns: listAdap, spacing: 0){
                            ForEach(listData, id: \.self){
                                item in
                                YMListCell(book: item,width: rootSize.size.width)
                            }
                        }.padding(EdgeInsets.init(top: 0, leading: 15, bottom: 0, trailing: 15))
                    }.padding(EdgeInsets.init(top:170, leading: 0, bottom: 0, trailing: 0))
                }.onAppear {
                    self.loadData()
                    self.loadShelfData()
                }.navigationBarTitle(model.title ?? "").navigationBarItems(leading: BaseNavigationBarBackButton(),trailing: YMChapterButton(bookId: bookId)).navigationBarBackButtonHidden(true)
                HStack.init(alignment: .center, spacing: 0) {
                    Button {
                        let have = quene.haveData(bookId)
                        if have{
                            self.isAlertActive = true
                        }else{
                            quene.insertData(bookId: bookId, bookInfo: model.toJSONString()) { success in
                                self.loadShelfData()
                            }
                        }
                    } label: {
                        Text(bookCase).foregroundColor(.black).font(Font(UIFont.boldSystemFont(ofSize: 18))).frame(width: rootSize.size.width/2, height: 49, alignment: .center).padding(EdgeInsets.init(top: 6, leading: 0, bottom: 0, trailing: 0))
                    }.alert(isPresented: $isAlertActive) {
                        Alert.init(title: Text("当前书本是否重书架中移除掉").font(Font.system(size: 18)).foregroundColor(.black), message: nil, primaryButton:Alert.Button.default(Text("取消").font(Font.system(size: 16)).foregroundColor(Color.appx999999()), action: {
                            
                        }), secondaryButton: Alert.Button.default(Text("确定").font(Font.system(size: 16)).foregroundColor(AppColor), action: {
                            quene.deleteData(bookId: bookId) { success in
                                self.loadShelfData()
                            }
                        }))
                    }
                    Button {
                        
                    } label: {
                        Text("立即阅读").foregroundColor(.white).font(Font.system(size: 18)).frame(width: rootSize.size.width/2, height: 49, alignment: .center)
                    }.background(AppColor)
                }.padding(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 0))
            }
        }
    }
    func loadData(){
        let group = DispatchGroup()
        group.enter()
        group.enter()
        var book   :YMBook?  = nil
        var books  :[YMBook] = []
        ApiMoya.request(target: .bookDetail(bookId)) { json in
            debugPrint(json)
            guard let model = YMBook.deserialize(from: json.rawString()) else{
                return
            }
            book = model
            group.leave()
        } failure: { error in
            group.leave()
        }
        ApiMoya.request(target: .commend(bookId)) { json in
            guard let list = [YMBook].deserialize(from: json["books"].rawString()) else { return  }
            if let datas = list as? [YMBook]{
                books = datas
            }
            group.leave()
        } failure: { error in
            group.leave()
        }
        group.notify(queue: DispatchQueue.main) {
            if let book = book {
                self.model = book
                historyQueue.updateBook(bookId: bookId, bookInfo: book.toJSONString() ?? "") { success in
                    
                }
            }
            self.listData = books
        }
    }
    func loadShelfData(){
        let have = quene.haveData(bookId)
        bookCase = have ? "已在书架" : "加入书架"
    }
}
struct YMDetailHeadView :View{
    var model :YMBook
    var body: some View{
        GeometryReader.init { rootSize in
            ZStack(alignment: .topLeading) {
      
                WebImage(url: URL(string: model.cover?.cover ?? "")).resizable().blur(radius: 40,opaque: true).frame(width: rootSize.size.width, height: 160, alignment: .center)
                HStack {
                    WebImage(url: URL(string: model.cover?.cover ?? "")).resizable().padding(EdgeInsets.init(top: 20, leading: 15, bottom: 0, trailing: 0)).frame(width: 100, height: 140, alignment: .center)
                    VStack(alignment: .leading, spacing: 10) {
                        Text(model.title ?? "").foregroundColor(.white).font(Font.system(size: 17)).padding(EdgeInsets.init(top: 15, leading: 0, bottom: 0, trailing: 0))
                        HStack(alignment: .center, spacing: 10) {
                            Text(model.author ?? "").font(Font.system(size: 14)).foregroundColor(.white).lineLimit(1)
                            Spacer()
                            Text(model.minorCate).padding(EdgeInsets(top: 3, leading: 6, bottom: 3, trailing: 6)).foregroundColor(.white).font(.system(size: 12)).lineLimit(1).overlay(RoundedRectangle(cornerRadius: 3, style: .continuous).stroke(.white, lineWidth: 1))
                            Text(model.majorCate).padding(EdgeInsets(top: 3, leading: 6, bottom: 3, trailing: 6)).foregroundColor(.white).font(.system(size: 12)).lineLimit(1).overlay(RoundedRectangle(cornerRadius: 3, style: .continuous).stroke(.white, lineWidth: 1))
                        }.padding(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 10))
                        Text(model.shortIntro ?? "").lineLimit(3).font(Font.system(size: 14)).foregroundColor(AppXDDDDDD)
                    }.padding(EdgeInsets.init(top: 0, leading: 10, bottom: 0, trailing: 0))
                }
            }
        }
    }
}
//                        ForEach(0 ..< model.tags.count) {
//                            Text(model.tags[$0]).padding(EdgeInsets(top: 3, leading: 6, bottom: 3, trailing: 6)).border(.white, width: 1).foregroundColor(.white).font(.system(size: 12)).lineLimit(1).cornerRadius(3)
//                        }
struct YMChapterButton :View {
    var bookId :String
    var body: some View{
        VStack {
            NavigationLink {
                YMChapterView(bookId:bookId)
            } label: {
                Text("目录").padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10)).foregroundColor(Color.appx333333()).font(.system(size: 16)).lineLimit(1).overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).stroke(AppXDDDDDD, lineWidth: 1))
            }
        }
    }
}
